package com.qf.realm;

import com.qf.pojo.SysRole;
import com.qf.pojo.SysUser;
import com.qf.service.SysMenuService;
import com.qf.service.SysRoleService;
import com.qf.service.SysUserService;
import com.qf.utils.MD5Utils;
import com.zaxxer.hikari.util.SuspendResumeLock;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("进来了。。。。。");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前登录的用户
        Subject subject = SecurityUtils.getSubject();
        //拿到user对象
        SysUser user = (SysUser) subject.getPrincipal();
        Long userId = user.getUserId();
        //查询用户得角色名称
        List<String> rolesByUserId = sysRoleService.findRolesByUserId(userId);
        //查询用户的菜单
        List<String> menuByUserId = sysMenuService.findMenuByUserId(userId);
        info.addRoles(rolesByUserId);
        info.addStringPermissions(menuByUserId);

        //设置权限

        return info;




    }

    //认证(登录验证)
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {


        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        SysUser byUsername = sysUserService.findByUsername(token.getUsername());
        if(byUsername == null){
            return null;
        }

        return new SimpleAuthenticationInfo(byUsername,byUsername.getPassword(),"");
    }

}
